<?php

namespace App\Models\Core;

use App\CorePlugs\AliyunSMS\SignatureHelper;
use App\Models\Model;
use Carbon\Carbon;


class CoreSMS extends Model
{
    protected $table = 'core_sms';
    protected $casts = [
        'result' => 'json',
        'fields' => 'json'
    ];


    // 开放的发送方法
    public static function sendsms($type, $mobile, array $fields){
        $sign = config('sms.sign');
        $templates = config('sms.template_type');
        $cur = new self();
        $cur->sign = $sign;
        $cur->template = $templates[$type];
        $cur->mobile = $mobile;
        $cur->fields = $fields;
        $result = $cur->finalSend();
        $cur->save();
        if($result->Code == 'OK'){
            return ['is_success'=>1, 'index'=> $cur->id, 'msg'=>'发送成功'];
        }
        return ['is_success'=>0, 'index'=> $cur->id, 'msg'=> $result->Message];
    }

    // 验证短信验证码
    public static function invalidCode($id, $code){
        $m = self::find($id);
        $res = ['r'=> false, 'msg'=> '验证码错误'];
        if(!empty($m)){
            if($m->fields['code'] != $code){
                $res['msg'] = '验证码错误';
                return $res;
            }
            if($m->status != 1){
                $res['msg'] = '验证码无效';
                return $res;
            }
            $diff = Carbon::now()->diffInSeconds(Carbon::parse($m->created_at));
            if($diff <  0 ||$diff > 10*60){
                $res['msg'] = '验证码失效';
                return $res;
            }
            $res['r'] = true;
            $m->status = 2;
            $m->save();
        }
        return $res;
    }

    //////////////////////
    /// 下面是调用接口 ////
    /// //////////////////
    private function finalSend() {
        $params = array ();
        // *** 需用户填写部分 ***
        $accessKeyId = config('sms.accessKeyId');
        $accessKeySecret = config('sms.accessKeySecret');
        $params["PhoneNumbers"] = $this->mobile;
        $params["SignName"] = $this->sign;
        $params["TemplateCode"] = $this->template;
        $params['TemplateParam'] = $this->fields;
        $params['OutId'] = "12345";
        $params['SmsUpExtendCode'] = "1234567";
        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }
        // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
        $helper = new SignatureHelper();
        // 此处可能会抛出异常，注意catch
        $content = $helper->request(
            $accessKeyId,
            $accessKeySecret,
            "dysmsapi.aliyuncs.com",
            array_merge($params, array(
                "RegionId" => "cn-hangzhou",
                "Action" => "SendSms",
                "Version" => "2017-05-25",
            ))
        // fixme 选填: 启用https
        // ,true
        );
        $this->result = $content;
        return $content;
    }

}
